<?php


class Core_FormController extends Zend_Controller_Action
{

	public function indexAction()
	{

    	$table = $this->_getModelInstance();

    	$tableIndex = $this->_getParam('model', 0);
		$primary = $table->getPrimary();
    	$foreignKeys = array(); //$table->getForeign();

		$id = intval($this->_getParam($primary));
		if($id == 0) {
			$item = $table->createRow();
			if($this->getRequest()->isPost()) {
				$item->setFromArray($this->getRequest()->getParam($table->getClass()));
			}
		} else {
			$where = array($primary . '= ?', $id);
			$collection = $table->find($where);
			$item = $collection->current();
		}

		// Lade Daten von der DB
		$session = $this->getHelper('Session');
        if($session->instance_id > 0) {
            $item->instance_id = $session->instance_id;
        }

		// Falls per GET ein Foreignkey übergeben wurde,
		// lade diesen Wert ebenfalls
		foreach($foreignKeys AS $fk) {
			$tmpFk = intval($this->_getParam($fk));
			if($tmpFk > 0) {
				if(intval($table->$fk) == 0) {
					$table->$fk = $tmpFk;
				}
			}
		}

		$this->view->redirect = $this->_getParam('redirect', $_SERVER['HTTP_REFERER']);
		$this->view->isPopup = ($this->_getParam('TEMPLATE') == 'popup');
		//$this->view->modelSelectUrl = $this->getDefaultEditUrl('#', $tableIndex);
		$this->view->model = $item;
		$this->view->formAction = $this->getDefaultSaveUrl($tableIndex);
		$this->view->tableInfos = $item->info();

    	//$this->render('edit2', null, true);

    	// Page Tree rendern
    	$moduleName = $this->getRequest()->getModuleName();
    	if((substr($moduleName, 0, 2) == 'xt') && ($moduleName != 'xtmodule')) {
			$this->render('container-tree', 'left', true);
    	}

		/*
		// TEST : begin -----------------------------------
		$editor = $item->getFormEditor();
		$editor->setFormAction($this->getDefaultSaveUrl());
		$editor->addSubmit(WSB_BTN_SAVE, array('label' => 'button:save'));
		$editor->addSubmit(WSB_BTN_SAVE_CLOSE, array('label' => 'button:save/close'));
		$editor->addButton(WSB_BTN_CANCEL, array('label' => 'button:cancel', 'onclick' => sprintf("javascript:window.location.href='%s';", $this->_getParam('redirect', $_SERVER['HTTP_REFERER']))));
		$editor->setRedirect($this->_getParam('redirect', $_SERVER['HTTP_REFERER']));
		$form = $editor->getForm();
		echo $form->render();
		// TEST: end    -----------------------------------
		*/
	}

}
